package com.hunan.api.catv.service.biz.system;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hunan.api.catv.entity.ServiceResult;
import com.hunan.api.catv.entity.po.SystemUser;
import com.hunan.api.catv.entity.vo.SystemUserVo;
import com.hunan.api.catv.service.ResultService;
import com.hunan.api.catv.service.impl.system.SystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;

@CacheConfig(cacheNames = "SystemUserBiz")
@Service
public class SystemUserBiz extends ResultService {

    @Autowired
    SystemUserService systemUserService;


    public PageInfo<SystemUserVo> page(int pageNum, int pageSize, String sysUserMail, Integer sysRoleId, Integer state) {
        PageHelper.startPage(pageNum, pageSize);
        SystemUser systemuser = new SystemUser();
        systemuser.setSysUserMail(sysUserMail);
        systemuser.setSysRoleId(sysRoleId);
        systemuser.setState(state);
        List<SystemUserVo> list = systemUserService.list(systemuser);
        return new PageInfo<SystemUserVo>(list);
    }

    public SystemUserVo info(Integer sysUserId) {
        SystemUserVo systemUserVo = systemUserService.getById(sysUserId);
        return systemUserVo;
    }

    public ServiceResult add(SystemUser systemUser) {
        String md5pwd = DigestUtils.md5DigestAsHex(systemUser.getSysUserPwd().getBytes());
        systemUser.setSysUserPwd(md5pwd);
        return systemUserService.add(systemUser);
    }

    public ServiceResult edit(SystemUser systemUser) {
        if (ObjectUtils.isEmpty(systemUser.getSysUserId())) {
            return buildFail("", "id not null");
        }
        if (!ObjectUtils.isEmpty(systemUser.getSysUserPwd())) {
            SystemUserVo systemUserVo = systemUserService.getById(systemUser.getSysUserId());
            if (!ObjectUtils.isEmpty(systemUserVo)) {
                if (!systemUser.getSysUserPwd().equals(systemUserVo.getSysUserPwd())) {
                    String md5pwd = DigestUtils.md5DigestAsHex(systemUser.getSysUserPwd().getBytes());
                    systemUser.setSysUserPwd(md5pwd);
                }
            }
        }
        return systemUserService.update(systemUser);
    }
}